const tools = require("../lib/tools") 
const $data = require("../data") 
const $axios =require('../lib/axios'); 
const qiniu =require('qiniu'); 
const $redis = require("../lib/redis") // 你的redis配置文件路径
const $weixin = require("../lib/weixin.js") ;
const md5 = require('md5-node');
module.exports = function (router) {

        // 配置login路由
        router.get('/snogogo_nuxt/api/login', async function (ctx, next) {
            ctx.body = "login"
        });

        // session info
        router.get('/snogogo_nuxt/api/userinfo', async function (ctx, next) {
        let sesData = await $data.sesData(ctx.sid)
        if(!sesData.uid){
            ctx.body = tools.response(0,{uid:0});
            return;
        }
        // ////console.log("sesData.uid:",sesData)
        let res = await  $data.getUser(sesData.uid)
        if(res.code==0 && res.data.uid){
            res.data.noti_count =await $data.notiCount( res.data.uid)
        }
        ctx.body =tools.response(res.code,res.msg,res.data);
        });
        // logout
        router.get('/snogogo_nuxt/api/logout', async function (ctx, next) {
        if(!ctx.sid){
            ctx.body = tools.response(0,"Not sign in");
            return;
        }

        const redis = ctx.redis;
        // ////console.log("sid:","sess:"+ctx.sid)
        let res = await redis.del("ses"+ctx.sid)
        ctx.body =tools.response(0,"ok",res);
        });


        // uploadToken
        // logout
        router.get('/snogogo_nuxt/api/uploadToken', async function (ctx, next) {
        let sid = ctx.sid;
        let sesData = await $data.sesData(sid)
        
        if(!sesData.uid && ctx.query.token!="D8J2sFGnq5yU5eXkmNFvBs2Kz29nTjdorTicPOe7"){
            ctx.body = tools.response(2,"Login Frist");
            return;
        }
        var accessKey = 'D8J2sFGnq5yU5eXkmNFvBs2Kz29nTjdorTicPOe7';
        var secretKey = 'FekuqLjHusWlpvL1ngThbGUiVhPsS2ul71Ow0x4J';
        var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
        var options = {
            scope: "sski",
            mimeLimit:"image/*"

        };
        var putPolicy = new qiniu.rs.PutPolicy(options);
        var uploadToken=putPolicy.uploadToken(mac);
        if( ctx.query.token){
            ctx.body ={
                uptoken: uploadToken
            };
        }else{
            ctx.body =tools.response(0,"ok",uploadToken);
        }
        
        });

         // uploadToken
        // logout
        router.get('/snogogo_nuxt/api/uploadTokenCh', async function (ctx, next) {
            let sid = ctx.sid;
            let sesData = await $data.sesData(sid)
            
            if(!sesData.uid && ctx.query.token!="D8J2sFGnq5yU5eXkmNFvBs2Kz29nTjdorTicPOe7"){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
            var accessKey = 'VMb-eB1eVABOCQtnxlFb9CvrneGKuzm2_wUdFMcE';
            var secretKey = '9cGg8RsXDmPEpagvhIB6y35GmhonTIf7xprObiEc';
            var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
            var options = {
                scope: "boxphp",
                mimeLimit:"image/*"
    
            };
            var putPolicy = new qiniu.rs.PutPolicy(options);
            var uploadToken=putPolicy.uploadToken(mac);
            if( ctx.query.token){
                ctx.body ={
                    uptoken: uploadToken
                };
            }else{
                ctx.body =tools.response(0,"ok",uploadToken);
            }
            
            });

        // 用户访问过的tag次数
        router.get('/snogogo_nuxt/api/user_read_tag', async function (ctx, next) {
            // const redis = ctx.redis;
            let tags =[];
            // ////console.log("ctx.request.body:",ctx.request.body,"tags:",tags)
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
            let uid = sesData.uid;
            // 访问
            if( ctx.query.tid){
                let res = await $data.getTopic( ctx.query.tid );
                tags = res.data.tag_values;
            }
            ////console.log("ctx.request.body:",ctx.query,"tags:",tags)
             if(tags.length==0 ){
                ctx.body =tools.response(2,"tags  is empty")  ;
                return;
            }
            let ok = $data.subscribeTag(uid,tags);
            ctx.body = tools.response(0,"ok",ok)  ;
        });

        // 获取用户常访问的tags
        router.get('/snogogo_nuxt/api/user_recommend_tag', async function (ctx, next) {
        let tags = await $data.getUserIndexTags(ctx.uid);
        ctx.body = tools.response(0,"suc",tags);
        
        })

         // 更新头像
         router.post('/snogogo_nuxt/user/update_picture', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
            let i = await $data.updateUser(sesData.uid,{
                uploadedpicture:ctx.request.body.picture,
                picture:ctx.request.body.picture,
            });
            if(i){
                let set = {};
                set["picture_"+sesData.uid] =ctx.request.body.picture;
                let r = await $redis.hset("username_picture",set);
            }
    
            ctx.body = tools.response(0,"suc",i);
        });
         // 更新用户名
         router.post('/snogogo_nuxt/user/update_user_name', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
            let res = await $data.updateUserName(sesData.uid,{
                username:ctx.request.body.username,
                password:ctx.request.body.password,
                uid:sesData.uid
            });

            ctx.body = tools.response(res['code'],res['msg'],res.data);
        });

         // 更新密码 
         router.post('/snogogo_nuxt/user/update_password', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
            let res = await $data.updatePassword(sesData.uid,{
                currentPassword:ctx.request.body.currentPassword,
                newPassword:ctx.request.body.newPassword
            });

            ctx.body = tools.response(res['code'],res['msg'],res.data);
        });
        // update a user account
        router.post('/snogogo_nuxt/user/update_account', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
            var params = ctx.request.body;
            var updateRaw={}
            var filterterms =["username","picture",'fullname','website','location','groupTitle','birthday','signature','aboutme']; //允许查询的字段 
            for (const key in params) {
                if(filterterms.indexOf(key)!=-1){
                    updateRaw[key] = params[key];
                }
            }
            ////console.log("updateRaw:",updateRaw);
            let res = await $data.updateAccount(sesData.uid,updateRaw);
            ctx.body = tools.response(0,"suc",res);
        });

        // update a user account
        router.post('/snogogo_nuxt/user/delete_account', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
            var password = ctx.request.body.password;
            let res = await $data.updatePassword(1,{
                "currentPassword": password,
                "newPassword": password
            });
            if(res.code>0){
                ctx.body = tools.response(res['code'],res['msg'],res.data);
                return;
            }
            res = await $data.deleteAccount(sesData.uid);
            ctx.body = tools.response(res['code'],res['msg'],res.data);
        });
        // unfollow
         // unfollow a user account
         router.post('/snogogo_nuxt/user/unfollow', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
           
          let  res = await $data.unFollowUser(ctx.request.body.uid,sesData.uid);
            ctx.body = tools.response(res['code'],res['msg'],res.data);
        });
         // follow a user account
         router.post('/snogogo_nuxt/user/follow', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
           
           let res = await $data.followUser(ctx.request.body.uid,sesData.uid);
            ctx.body = tools.response(res['code'],res['msg'],res.data);
        });

         // noti_count
         router.get('/snogogo_nuxt/user/noti_count', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
           let count = await $redis.zscan("uid:"+sesData.uid+":notifications:unread")
           ctx.body = tools.response(0,"suc",count);
        });
// create user
        router.post('/snogogo_nuxt/create_user', async function (ctx, next) {
            let  res = await $data.createUser(ctx.request.body);
            ctx.body = tools.response(res['code'],res['msg'],res.data);
        });
       
        // validate a user's email address
        router.post('/snogogo_nuxt/user/validate_email', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
            let  res = await $data.validateEmail(sesData.uid,ctx.request.body.email);
            ctx.body = tools.response(res['code'],res['msg'],res.data);
        });

        // resetSend 
          // resetSend 发送重置密码邮件
        router.post('/snogogo_nuxt/user/reset', async function (ctx, next) {
            if(!ctx.request.body.email){
                ctx.body = tools.response(1,"Invalid Email");
                return;
            }
            if(ctx.request.body.recaptcha_type=="" || ctx.request.body.recaptcha_response==""){
                ctx.body = tools.response(1,"Invalid Recaptcha");
                return;
            }
            let p ={
                email:ctx.request.body.email,
                recaptcha_response:ctx.request.body.recaptcha_response,
                recaptcha_type:ctx.request.body.recaptcha_type,
            }
            let  res = await $data.resetSend(p);
            let data = {
                uid:res.data.uid
            }
            ctx.body = tools.response(res['code'],res['msg'],data);
        });
     

          


         // resetPwdByCode 重置密码通过邮件
         router.post('/snogogo_nuxt/user/resetPwdByCode', async function (ctx, next) {
            if(!ctx.request.body.code){
                ctx.body = tools.response(1,"Invalid Code");
                return;
            }
            let p ={
                "update_pwd_code":ctx.request.body.code,
                "birthday":"1989-10-01",
                "newPassword": ctx.request.body.password, 
            }
            let  res = await $data.updateAccount(1,p);
            let data = {
                uid:res.data.uid
            }
            ctx.body = tools.response(res['code'],res['msg'],data);
        });

         // createUserCategory
         router.post('/snogogo_nuxt/user/createUserCategory', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
            let  res = await $data.createUserCategory(sesData.uid,ctx.request.body.categoryName);
            ctx.body = tools.response(0,"suc","");
        });

         // createUserCategory
         router.get('/snogogo_nuxt/user/getUserCategory', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
            let  res = await $data.getUserCategory(sesData.uid,0,30);
            ctx.body = tools.response(0,"suc",res);
        });

        // resetPwdByCode 重置密码通过邮件
        router.post('/snogogo_nuxt/user/sendValidationEmail', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
           
            let p ={
                "type":ctx.request.body.type,
                "birthday":"1989-10-01",
                "email": ctx.request.body.email, 
                "password":ctx.request.body.password,
                "uid": sesData.uid, 
                "recaptcha_response":ctx.request.body.recaptcha_response,
                "recaptcha_type":ctx.request.body.recaptcha_type,
            }
            let  res = await $data.updateAccount(1,p);
            let data = {
                uid:res.data.uid
            }
            ctx.body = tools.response(res['code'],res['msg'],data);
        });

         // 微信小程序Login
        router.post('/apiv2/user/loginByWxApp', async function (ctx, next) {
            let userinfo ={};
            if(!ctx.request.body.code){
                ctx.body = tools.response(1,"Invalid Code");
                return;
            }
            try{
              userinfo =  JSON.parse(ctx.request.body.rawData, true);
            }catch($e){
               ctx.body = tools.response(1,"Invalid user rawData");
               return;
            }
            let res =  await $weixin.code2Session(ctx.request.body.code);
            if(res.code>0){
                ctx.body = tools.response(2,"Invalid Code:"+res.msg);
                return;
            }
            userinfo.openid = res.data.openid;
            userinfo.session_key = res.data.session_key;
            // 
            let uid = await   $redis.get("uid:openid:"+userinfo.openid);
            if(!uid){
                // 注册用户
                let p= {
                    "username": userinfo.nickName,
                    "password": userinfo.openid,
                    "picture":userinfo.avatarUrl,
                    'SnoGoGoApikey':'09bcedd8-7ae1-42e0-a8c5-199f038b8952'
                    };
                
                let userRes = await $data.createUser(p);
                if(userRes.code>0){
                    ctx.body = tools.response(3,"登录失败:"+userRes.msg);
                    return;
                }
                uid = userRes.data.uid;
                $redis.set("uid:openid:"+userinfo.openid,uid)
                $redis.set("uid:openid:"+uid,userinfo.openid);
            }

            let userRes = await $data.getUser(uid);
            if(userRes.code>0){
                ctx.body = tools.response(4,"用户查询失败:"+userRes.msg);
                return;
            }
            
            let user = userRes.data;
            user.openid = userinfo.openid;
            // 设置登录信息
            let token = ":"+md5(JSON.stringify(user));
            let ses={
                passport: {
                    user:uid
                },
                 meta:{
                    uuid:user.openid
                 }
            }
            $redis.set("ses"+token, JSON.stringify( ses));
            user.token =token; 
            ctx.body = tools.response(0,"成功",user);

        });

        router.post('/apiv2/user/checkToken', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
            
            ctx.body = tools.response(0,"成功",sesData.uid);
        })

        router.post('/apiv2/user/bindwxphone', async function (ctx, next) {
            let sesData = await $data.sesData(ctx.sid)
            if(!sesData.uid){
                ctx.body = tools.response(2,"Login Frist");
                return;
            }
           
            if(!ctx.request.body.code){
                ctx.body = tools.response(1,"Invalid Code");
                return;
            }
            let code = ctx.request.body.code;
            let res =  await $weixin.getuserphonenumber(code);
            if(res.code>0){
                ctx.body = tools.response(res.code,res.msg,res.data);
                return;
            }

            $redis.set("uid:phone:"+sesData.uid,res.data.phone_info.phoneNumber);
             

            ctx.body = tools.response(0,"成功",res.data.phone_info.phoneNumber);
        })
        
        
        
         

}